//
//  RackCommentCell.m
//  danpin
//
//  Created by chuangjia on 17/12/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "RackCommentCell.h"

#import "TTTAttributedLabel.h"
#import "UIButtonView.h"
#import "CalcLabel.h"
#import "ReplayView.h"
@interface RackCommentCell ()
{
    
}
@property(nonatomic,strong)UIImageView *imagesView;
@property(nonatomic,strong)RTLabel *titleLabel;
@property(nonatomic,strong)TTTAttributedLabel *contentLabel;
@property(nonatomic,strong)UILabel *time;
@property(nonatomic,strong)UIButtonView *btnLike;
@property(nonatomic,strong)UIButtonView *btnReply;
@property(nonatomic,strong)UIButton *btnReport;
@property(nonatomic,strong)UIImageView *lineView;

@end
@implementation RackCommentCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.backgroundColor=[UIColor clearColor];
        UITapGestureRecognizer* singleRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFromUser)];
        _imagesView =[[UIImageView alloc] initWithFrame:CGRectZero];
        _imagesView.layer.cornerRadius=PHOTO_FRAME_WIDTH*2;
        _imagesView.layer.masksToBounds = YES;
        _imagesView.userInteractionEnabled=YES;
        [_imagesView addGestureRecognizer:singleRecognizer];
        [self.contentView addSubview:_imagesView];
        singleRecognizer=nil;
        
        UITapGestureRecognizer* singleRecognizer1= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFromUser)];
        _titleLabel =[[RTLabel alloc] initWithFrame:CGRectMake(0,0, DEVICE_WIDTH-(PHOTO_FRAME_WIDTH+PHOTO_TIME_PADDING)*2,0)];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textColor = UIColorFromRGB(0x285790);
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.font = FONT(13);
        _titleLabel.lineSpacing =LSpacing;
        _titleLabel.userInteractionEnabled=YES;
        [_titleLabel addGestureRecognizer:singleRecognizer1];
        [self.contentView addSubview:_titleLabel];
        singleRecognizer1=nil;
        //
        _time =[[UILabel alloc] initWithFrame:CGRectZero];
        _time.backgroundColor = [UIColor clearColor];
        _time.textColor = UIColorFromRGB(0xcccccc);
        _time.textAlignment = NSTextAlignmentLeft;
        _time.font = FONT(10);
        _time.numberOfLines=0;
        [self.contentView addSubview:_time];
        
        _contentLabel =[[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0,0, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*6,0)];
        _contentLabel.backgroundColor = [UIColor clearColor];
        _contentLabel.textColor = [UIColor darkGrayColor];
        _contentLabel.textAlignment = NSTextAlignmentLeft;
        _contentLabel.font = FONT(13);
        _contentLabel.lineBreakMode = NSLineBreakByWordWrapping|NSLineBreakByTruncatingTail;
        _contentLabel.numberOfLines=0;
        [self.contentView addSubview:_contentLabel];
        
        
        _btnLike = [[UIButtonView alloc] initWithFrame:CGRectZero];
        _btnLike.backgroundColor =  [UIColor clearColor];
        __weak typeof (self) wSelf = self;
        [_btnLike setCallBack:^(BEventType t, UIView *v, id data, id key) {
            [wSelf likeAction:nil];
            
            [UIView animateWithDuration:0.5f animations:^{
                wSelf.btnLike.transform = CGAffineTransformMakeScale(1.5, 1.5);
            } completion:^(BOOL finished) {
                
                wSelf.btnLike.transform = CGAffineTransformMakeScale(1, 1);
            }];
            
        }];
        [self.contentView addSubview:_btnLike];
        
        _btnReply = [[UIButtonView alloc] initWithFrame:CGRectZero];
        _btnReply.backgroundColor =  [UIColor clearColor];
        [_btnReply setCallBack:^(BEventType t, UIView *v, id data, id key) {
            [wSelf commentAction:nil];
            
            [UIView animateWithDuration:0.5f animations:^{
                wSelf.btnReply.transform = CGAffineTransformMakeScale(1.5, 1.5);
            } completion:^(BOOL finished) {
                
                wSelf.btnReply.transform = CGAffineTransformMakeScale(1, 1);
            }];
            
        }];
        [self.contentView addSubview:_btnReply];
        
        _btnReport = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnReport.backgroundColor =  [UIColor clearColor];
        _btnReport.titleLabel.font =FONT(12);
        _btnReport.tag =3;
        [_btnReport setImage:[UIImage imageNamed:@"more_icon.png"] forState:UIControlStateNormal];
        [_btnReport addTarget:self action:@selector(showMenu:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_btnReport];
        
        
        _lineView =[[UIImageView alloc] initWithFrame:CGRectZero];
        _lineView.backgroundColor=UIColorFromRGB(0xe5e5e5);
        [self.contentView addSubview:_lineView];
        
        
    }
    return self;
}
-(void)dealloc
{
    self.actionBlock =nil;
    self.data=nil;
    self.indexPath=nil;
    self.other=nil;
    self.key=nil;
    self.imagesView.image=nil;
    [self.imageView removeFromSuperview];
    self.imagesView=nil;
    [self.titleLabel removeFromSuperview];
    self.titleLabel=nil;
    [self.btnLike removeFromSuperview];
    self.btnLike=nil;
    [self.contentLabel removeFromSuperview];
    self.contentLabel=nil;
    [self.lineView removeFromSuperview];
    self.lineView =nil;
    
    //    DLog(@"%s", __PRETTY_FUNCTION__);
}
- (void)drawRect:(CGRect)rect {
    
    [super drawRect:rect];
    self.lineView.frame =CGRectMake(0,self.bounds.size.height-0.5, DEVICE_WIDTH, 0.5);
}
- (void)layoutSubviews
{
    [super layoutSubviews];
//    {
//        "comment_date" = "2015-12-17 10:22:37";
//        "comment_dateinfo" = "58\U5206\U949f\U524d";
//        "comment_id" = 4992;
//        from = 0;
//        "had_bottom" = 0;
//        "had_top" = 0;
//        largeFace = "http://storage.jd.com/i.imageUpload/6a645f3564343564346431346539303931333938373232313234313632_sma.jpg";
//        middleFace = "http://storage.jd.com/i.imageUpload/6a645f3564343564346431346539303931333938373232313234313632_sma.jpg";
//        "nick_name" = "\U501a\U5929\U662f\U4e0d\U51fa";
//        parent =             (
//        );
//        "photo_id" = 1016507;
//        "push_bottom" = 1;
//        "push_top" = 0;
//        "rank_id" = "<null>";
//        smallFace = "http://storage.jd.com/i.imageUpload/6a645f3564343564346431346539303931333938373232313234313632_sma.jpg";
//        text = "\U5475\U5475";
//        "user_id" = 237502;
//    }
    
}
/// 根据数据模型来显示内容
- (void)showInfo:(id)model key:(id)key indexPath:(NSIndexPath *)indexPath
{
    self.key =key;
    self.indexPath=indexPath;
    NSDictionary *dict =(NSDictionary*)model;
    self.data =model;
    if (dict && [dict isKindOfClass:[NSDictionary class]]) {
        _imagesView.frame =CGRectMake(PHOTO_FRAME_WIDTH,PHOTO_FRAME_WIDTH, PHOTO_FRAME_WIDTH*4, PHOTO_FRAME_WIDTH*4);
        NSString * strURL =[dict stringForKey:@"middleFace" withDefaultValue:@""];
        if (strURL.length>0) {
            [_imagesView sd_setImageWithURL:[NSURL URLWithString:strURL] placeholderImage:[UIImage imageNamed:@"user_face.png"]];
        }
        
        NSString *test =[dict stringForKey:@"nick_name" withDefaultValue:@""];
        _titleLabel.text =test;
        _titleLabel.frame =CGRectMake(_imagesView.frame.origin.x+_imagesView.frame.size.width+PHOTO_FRAME_WIDTH, _imagesView.frame.origin.y,DEVICE_WIDTH/2, 20);
        //time
        NSString *msg_date = [dict stringForKey:@"comment_dateinfo" withDefaultValue:@""];
        if (msg_date.length>0) {
            _time.text =msg_date;
            CGSize sizetime =[_time boundingRectWithSize:CGSizeMake(DEVICE_WIDTH, PHOTO_FRAME_WIDTH*2)];
            _time.frame=CGRectMake(_titleLabel.frame.origin.x,_titleLabel.frame.origin.y + _titleLabel.frame.size.height,
                                   sizetime.width,
                                   PHOTO_FRAME_WIDTH*2);
        }
        
    }
    
    //
    NSString *content =[dict stringForKey:@"text" withDefaultValue:@""];
    if (content.length>0) {
        [_contentLabel setText:content afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString  *(NSMutableAttributedString *attributedString)
         {
             [attributedString addAttribute:NSFontAttributeName
                                      value:FONT(13)
                                      range:NSMakeRange(0,[attributedString length])];
             //设置字体颜色
             [attributedString addAttribute:(id)kCTForegroundColorAttributeName value:TITLE_COLOR range:NSMakeRange(0,[attributedString length])];
             
             CGFloat lineSpace = 3.0f;
             CTParagraphStyleSetting lineSpaceStyle;
             lineSpaceStyle.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
             lineSpaceStyle.valueSize = sizeof(lineSpace);
             lineSpaceStyle.value =&lineSpace;
             
             //创建设置数组
             CTParagraphStyleSetting settings[ ] ={lineSpaceStyle};
             CTParagraphStyleRef style = CTParagraphStyleCreate(settings ,1);
             
             //给文本添加设置
             [attributedString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)CFBridgingRelease(style) range:NSMakeRange(0 , [attributedString length])];
             return attributedString;
             
         }];
        
        float fheight = [CalcLabel getAttributedStringHeightWidthValue:(DEVICE_WIDTH-PHOTO_FRAME_WIDTH*8) str:_contentLabel.attributedText];
        _contentLabel.frame =CGRectMake(_imagesView.frame.origin.x+_imagesView.frame.size.width+PHOTO_FRAME_WIDTH, _titleLabel.frame.origin.y+_titleLabel.frame.size.height+ _time.frame.size.height + PHOTO_TIME_PADDING, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*7, fheight);
    }
    //
    CGFloat y = _titleLabel.frame.origin.y;//_contentLabel.frame.origin.y+_contentLabel.frame.size.height+PHOTO_FRAME_WIDTH;
    
    
    _btnReport.frame=CGRectMake(DEVICE_WIDTH-30-PHOTO_FRAME_WIDTH, y,30, MORE_BUTTON_HEIGHT);
    
    NSString *reply_cnt =[dict stringForKey:@"push_bottom" withDefaultValue:@""];
    
    if (reply_cnt.length>0&&![reply_cnt isEqualToString:@"0"]&&![reply_cnt isEqualToString:@"<null>"]) {
        [_btnReply setImage:[UIImage imageNamed:@"hand_down_cheackout"] name:reply_cnt];
    }else
    {
        reply_cnt =@"0";
        [_btnReply setImage:[UIImage imageNamed:@"hand_down"] name:@"0"];
    }
    CGSize size=[reply_cnt sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0]}];
    _btnReply.frame=CGRectMake(_btnReport.frame.origin.x -(size.width+40)-PHOTO_FRAME_WIDTH, y, size.width+40, MORE_BUTTON_HEIGHT);
    
    int had_bottom=[[dict numberStringForKey:@"had_bottom"] intValue];
    if (had_bottom>0) {
        [_btnReply setImage:[UIImage imageNamed:@"hand_down_cheackout"] name:reply_cnt];
    }
    NSString *like_cnt =[dict stringForKey:@"push_top" withDefaultValue:@""];
    if (like_cnt.length>0&&![like_cnt isEqualToString:@"0"]&&![like_cnt isEqualToString:@"<null>"]) {
        [_btnLike setImage:[UIImage imageNamed:@"hand_up_cheackoue"] name:like_cnt];
    }else
    {
        like_cnt =@"0";
        [_btnLike setImage:[UIImage imageNamed:@"hand_up"] name:@"0"];
    }
    CGSize size0=[like_cnt sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0]}];
    _btnLike.frame=CGRectMake(_btnReply.frame.origin.x-(size0.width+40)-PHOTO_FRAME_WIDTH, y,size0.width+40, MORE_BUTTON_HEIGHT);
    
    int had_top=[[dict numberStringForKey:@"had_top"] intValue];
    if (had_top>0) {
        [_btnLike setImage:[UIImage imageNamed:@"hand_down_cheackout"] name:like_cnt];
    }
    //
    id parent = [dict objectForKey:@"parent"];
    if (parent && [parent isKindOfClass:[NSArray class]] && [parent count]>0) {
        CGFloat parentheight = 0.0;
        for (NSDictionary *dict in parent) {
            CGFloat tempH = 40;
            NSString *text =[dict stringForKey:@"text" withDefaultValue:@""];
            if (text.length>0) {
                text =[NSString stringWithFormat:@"“%@”",text];
                
                NSMutableAttributedString* attributedString =[[NSMutableAttributedString alloc]initWithString:text];
                [attributedString addAttribute:NSFontAttributeName value:FONT(13) range:NSMakeRange(0,[attributedString length])];
                
                CGFloat lineSpace = 3.0f;
                CTParagraphStyleSetting lineSpaceStyle;
                lineSpaceStyle.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
                lineSpaceStyle.valueSize = sizeof(lineSpace);
                lineSpaceStyle.value =&lineSpace;
                //创建设置数组
                CTParagraphStyleSetting settings[ ] ={lineSpaceStyle};
                CTParagraphStyleRef style = CTParagraphStyleCreate(settings ,1);
                
                //给文本添加设置
                [attributedString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)CFBridgingRelease(style) range:NSMakeRange(0 , [attributedString length])];
                float fheight = [CalcLabel getAttributedStringHeightWidthValue:(DEVICE_WIDTH- PHOTO_FRAME_WIDTH*8) str:attributedString];
                if (fheight<20)
                {
                    fheight=20;
                }
                attributedString = nil;
                parentheight =parentheight +tempH+ fheight;
            }
        }
        CGFloat ytop = _contentLabel.frame.origin.y+_contentLabel.frame.size.height+PHOTO_FRAME_WIDTH;
        ReplayView *tempView =[[ReplayView alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH*6, ytop, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*7, parentheight) dataDict:parent];
        [self.contentView addSubview:tempView];
        tempView=nil;
    }
    
    [self layoutSubviews];
}
-(void)setCallBack:(void(^)(BEventType,UIView*,id,id,NSIndexPath *))callback
{
    self.actionBlock=callback;
}
-(void)likeAction:(id)sender
{
    if (self.actionBlock) {
        self.actionBlock(BEventType_ding,sender,self.data,nil,self.indexPath);
    }
}
-(void)commentAction:(id)sender
{
    if (self.actionBlock) {
        self.actionBlock(BEventType_cai,sender,self.data,nil,self.indexPath);
    }
}

-(void)handleSingleTapFrom
{
    if (self.actionBlock) {
        self.actionBlock(BEventType_comment,nil,self.data,nil,self.indexPath);
    }
}
-(void)handleSingleTapFromUser
{
    if (self.actionBlock) {
        self.actionBlock(BEventType_sunUser,nil,self.data,nil,self.indexPath);
    }
}
/// 返回Cell高度
+ (CGFloat)returnCellHeight:(id)model
{
    NSDictionary *dict =(NSDictionary *)model;
    float hight =20;
    NSString *text =[dict stringForKey:@"text" withDefaultValue:@""];
    if (text.length>0) {
        text =[NSString stringWithFormat:@"%@",text];
        
        NSMutableAttributedString* attributedString =[[NSMutableAttributedString alloc]initWithString:text];
        [attributedString addAttribute:NSFontAttributeName value:FONT(13) range:NSMakeRange(0,[attributedString length])];
   
        CGFloat lineSpace = 3.0f;
        CTParagraphStyleSetting lineSpaceStyle;
        lineSpaceStyle.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
        lineSpaceStyle.valueSize = sizeof(lineSpace);
        lineSpaceStyle.value =&lineSpace;
        
        //创建设置数组
        CTParagraphStyleSetting settings[ ] ={lineSpaceStyle};
        CTParagraphStyleRef style = CTParagraphStyleCreate(settings ,1);
        
        //给文本添加设置
        [attributedString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)CFBridgingRelease(style) range:NSMakeRange(0 , [attributedString length])];
        float fheight = [CalcLabel getAttributedStringHeightWidthValue:(DEVICE_WIDTH- PHOTO_FRAME_WIDTH*8) str:attributedString];
        if (fheight<20)
        {
            fheight=20;
        }
        attributedString = nil;
        hight =hight + fheight;
    }
    CGFloat parentheight = 0;
    id parent = [dict objectForKey:@"parent"];
    if (parent && [parent isKindOfClass:[NSArray class]] && [parent count]>0) {
        NSMutableArray *parentarray = [NSMutableArray arrayWithArray:parent];
        for (NSDictionary *dict in parentarray) {
            CGFloat tempH = 40;
            NSString *text =[dict stringForKey:@"text" withDefaultValue:@""];
            if (text.length>0) {
                text =[NSString stringWithFormat:@"“%@”",text];
                
                NSMutableAttributedString* attributedString =[[NSMutableAttributedString alloc]initWithString:text];
                [attributedString addAttribute:NSFontAttributeName value:FONT(13) range:NSMakeRange(0,[attributedString length])];
                
                CGFloat lineSpace = 3.0f;
                CTParagraphStyleSetting lineSpaceStyle;
                lineSpaceStyle.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
                lineSpaceStyle.valueSize = sizeof(lineSpace);
                lineSpaceStyle.value =&lineSpace;
                //创建设置数组
                CTParagraphStyleSetting settings[ ] ={lineSpaceStyle};
                CTParagraphStyleRef style = CTParagraphStyleCreate(settings ,1);
                
                //给文本添加设置
                [attributedString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)CFBridgingRelease(style) range:NSMakeRange(0 , [attributedString length])];
                float fheight = [CalcLabel getAttributedStringHeightWidthValue:(DEVICE_WIDTH- PHOTO_FRAME_WIDTH*8) str:attributedString];
                if (fheight<20)
                {
                    fheight=20;
                }
                attributedString = nil;
                parentheight =parentheight +tempH+ fheight;
            }
        }
        hight =hight +parentheight;
    }
    return PHOTO_FRAME_WIDTH*4+hight + PHOTO_FRAME_WIDTH;
    
}

- (void)showMenu:(UIButton *)sender
{
    if (self.actionBlock) {
        self.actionBlock(BEventType_comment,nil,self.data,nil,self.indexPath);
    }
}

@end
